import store from '@/store'
import GOLOBALINFO from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import md5 from "@/utils/md5.js";
let timeout = 10000
const baseUrl = GOLOBALINFO.baseUrl + '/api/app/appupload?path=/upload/avatar/'

const upload = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header[GOLOBALINFO.appInfo.TOKEN_NAME] = GOLOBALINFO.appInfo.TOKEN_PREFIX + getToken()
	}
	const timestamp = new Date().getTime();
	config.header["appkey"] = GOLOBALINFO.appInfo.APP_KEY;
	config.header["timestamp"] = timestamp;
	config.header["App"] = 'userApp';
	const signStr =
		GOLOBALINFO.APP_KEY +
		GOLOBALINFO.SIGN_KEY +
		timestamp +
		JSON.stringify(config.data);
	config.header["signature"] = md5.hex_md5(signStr);
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	let fileName = config['fileName']
	console.log("config", config);
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			timeout: config.timeout || timeout,
			url: baseUrl + (fileName == undefined ? '' : fileName),
			header: config.header,
			// #ifdef H5
			files: [{
				name: 'file', // 传给后端时二进制文件的key
				file: config.filePath,
				url: config.filePath.path,
			}],
			// #endif

			// #ifdef MP || APP
			filePath: config.filePath.path, // 本地文件地址
			name: 'file', // 传给后端时二进制文件的key
			// #endif

			formData: config.formData,
			success: (res) => {
				console.log("res", res);
				let result = res.data ? JSON.parse(res.data) : ''
				const code = result.code || res.statusCode || 200
				const msg = errorCode[code] || result.message || errorCode['default']
				if (code == 200) {
					resolve(result)
				} else if (code == 401) {
					showConfirm("登录状态已过期，请重新登录!").then(res => {
						if (res.confirm) {
							uni.setStorageSync('manPorUserInfo', '')
							uni.setStorageSync('psyTages', '')
							uni.setStorageSync('psyId', '')
							uni.setStorageSync('adjTages', '')
							uni.setStorageSync('userToken', '')
							uni.setStorageSync('manPorLoginconfig', '')
							uni.setStorageSync('manPorUserInfo', '')
							uni.setStorageSync('manPorArea', '')
							uni.reLaunch({
								url: '/pages/login'
							})
						}
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code == 500) {
					toast(msg)
				} else if (code != 200) {
					toast(msg)
				}
				resolve(result)
			},
			fail: (error) => {
				let message = error.errMsg
				console.log("error", message);
				if (message == 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else {
					message = '系统接口异常'
				}
				toast(message)
				reject(error)
			}
		})
	})
}

export default upload